#include <iostream>
#include <winsock2.h>
#include <string>
#include <regex>
#pragma comment(lib, "ws2_32.lib")

int main()
{
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET)
    {
        std::cerr << "Failed to create socket." << std::endl;
        return 1;
    }

    sockaddr_in serverAddress;
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(8080); // 监听端口号
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    if (bind(sock, (const struct sockaddr *)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR)
    {
        std::cerr << "Failed to bind socket." << std::endl;
        closesocket(sock);
        return 1;
    }

    if (listen(sock, SOMAXCONN) == SOCKET_ERROR)
    {
        std::cerr << "Failed to listen on socket." << std::endl;
        closesocket(sock);
        return 1;
    }

    std::cout << "Server listening on port 8080..." << std::endl;

    while (true)
    {
        SOCKET clientSocket = accept(sock, NULL, NULL);
        if (clientSocket == INVALID_SOCKET)
        {
            std::cerr << "Failed to accept connection." << std::endl;
            continue;
        }

        char buffer[1024];
        int bytesRead;
        bool flag = true;
        while (flag)
        {
            int bytesRead = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
            buffer[bytesRead] = '\0';
            if (bytesRead == -1)
            {
                int error = WSAGetLastError();
                std::cerr << "Failed to read from client: " << error << std::endl;
                break;
            }
            else if (bytesRead == 0)
            {
                const char *response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello, World!";
                send(clientSocket, response, strlen(response), 0);
                break;
            }
            else
            {
                std::cout << buffer;
            }
        }
        closesocket(clientSocket);
    }

    closesocket(sock);
    WSACleanup();
    return 0;
}